package com.littleu.market.controller.cms;

import com.littleu.market.dto.user.LoginDTO;
import com.littleu.market.model.UserDO;
import com.littleu.market.service.IUserIdentityService;
import com.littleu.market.service.IUserService;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.autoconfigure.exception.ParameterException;
import io.github.talelin.core.token.DoubleJWT;
import io.github.talelin.core.token.Tokens;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cms/user")
@Validated
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserIdentityService userIdentityService;

    @Autowired
    private DoubleJWT jwt;
    /**
     * 用户注册
     */


    /**
     * 用户登陆
     */
    @PostMapping("/login")
    public Tokens login(@RequestBody @Validated LoginDTO validator){
        UserDO userDO = userService.getUserByUsername(validator.getUsername());
        if(userDO == null){
            throw new NotFoundException(10021);
        }
        boolean valid = userIdentityService.verifyUsernamePassword(
                userDO.getId(),
                userDO.getUsername(),
                validator.getPassword()
        );
        if(!valid){
            throw new ParameterException(10031);
        }
        return jwt.generateTokens(userDO.getId());
    }

}
